import CryptoJS from 'crypto-js'

// 默认的KEY与iv与后端保持一致，不采用后端传值密钥
const KEY = CryptoJS.enc.Utf8.parse('DSHGFYSEJFBJKDJSFHUWERYU') // 密钥
const IV = CryptoJS.enc.Utf8.parse('DSHGFYSEJFBJKDJS') // 偏移量
export const md5 = (value) => {
	return CryptoJS.MD5(value).toString()
}

/** AES加密 */
export function Encrypt(word) {
	let key = KEY
	let iv = IV

	const srcs = CryptoJS.enc.Utf8.parse(word)
	var encrypted = CryptoJS.AES.encrypt(srcs, key, {
		iv: iv,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.ZeroPadding,
	})

	return CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
}

/** AES 解密 */
export function Decrypt(word) {
	let key = KEY
	let iv = IV

	const base64 = CryptoJS.enc.Base64.parse(word)
	const src = CryptoJS.enc.Base64.stringify(base64)

	var decrypt = CryptoJS.AES.decrypt(src, key, {
		iv: iv,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.ZeroPadding,
	})

	var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)

	return JSON.parse(decryptedStr)
}
